package com.atguigu.msmservice.service.controller;

import com.atguigu.commonutils.R;
import com.atguigu.msmservice.service.MsmService;
import com.atguigu.msmservice.utils.RandomUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/edumsm/msm")
@CrossOrigin
public class MsmController {

    @Autowired
    private MsmService msmService;

    @Autowired
    private RedisTemplate<String,String> redisTemplate;

    //发送短信的方法
    @GetMapping("send/{phone}")
    public R sendMsm(@PathVariable String phone) {
        //1 从redis获取验证码，如果获取到直接返回
        String code = redisTemplate.opsForValue().get(phone);
        if(!StringUtils.isEmpty(code)) {
            return R.ok();
        }
        //2 如果redis获取 不到，进行阿里云发送
        //生成随机值，传递阿里云进行发送
        code = RandomUtil.getFourBitRandom(); //生成一个四位数的验证码
        Map<String,Object> param = new HashMap<>(); //将验证码放到map集合中
        param.put("code",code);
        //调用service发送短信的方法
        boolean isSend = msmService.send(param,phone);
        if(isSend) {
            //发送成功，把发送成功验证码放到redis里面
            //设置有效时间
            redisTemplate.opsForValue().set(phone,code,5, TimeUnit.MINUTES);
            return R.ok();
        } else {
            return R.error().message("短信发送失败");
        }
    }



    @RestController
    @RequestMapping("/edusms/sms")
    @CrossOrigin
    public class SmsController {

        @Autowired
        JavaMailSenderImpl mailSender;

        @Autowired
        private RedisTemplate<String,String> redisTemplate; //redis模板

        @PostMapping("sendEmail/{DstEmail}")
        public R sendEmail(@PathVariable String DstEmail) {
            //从redis中获取验证码，如果获取到直接返回
            String verCode = redisTemplate.opsForValue().get(DstEmail);
            if (!StringUtils.isEmpty(verCode)){
                return R.ok();
            }
            //如果获取不到，进行邮箱发送
            //创建邮件消息
            SimpleMailMessage message = new SimpleMailMessage();
            //发送人邮箱
            message.setFrom("616342388@qq.com");
            //接收人邮箱
            message.setTo(DstEmail);
            message.setSubject("[若晨学院]");
            verCode = RandomUtil.getSixBitRandom();
            message.setText("您好:\n"
                    + "\n本次请求的邮件验证码为:" + verCode + ",本验证码 5 分钟内效，请及时输入。（请勿泄露此验证码）\n"
                    + "\n如非本人操作，请忽略该邮件。\n(这是一封通过自动发送的邮件，请不要直接回复）");
            mailSender.send(message);
            //把发送成功的验证码存放到redis里面
            //设置有效时间
            redisTemplate.opsForValue().set(DstEmail,verCode,5, TimeUnit.MINUTES);
            return R.ok();
        }
    }
}
